package com.epfresh.supplier.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.User;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ShareDialog;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.EnsureCompanyActivity;
import com.epfresh.supplier.activity.EnsurePersonActivity;
import com.epfresh.supplier.activity.ForgetPasdActivity;
import com.epfresh.supplier.activity.LoginActivity;
import com.epfresh.supplier.activity.MyInfoActivity;
import com.epfresh.supplier.activity.SelectNameEnsureActivity;
import com.epfresh.supplier.activity.SetActivity;
import com.epfresh.supplier.activity.WebActivity;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.CertInfo;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.MineCertStatusEvenbus;
import com.epfresh.supplier.entity.StoreBaseInfo;
import com.epfresh.supplier.widget.IosAlertDialog;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/*
        addressText = (TextView)v.findViewById(R.id.address_text);
        addressText.setOnClickListener(this);
*/

/**
 * Created by wzh on 2016/5/4.
 */
public class MineFragment extends BaseFragment {

    private ImageView headImage;
    private TextView nicknameTV;
    private TextView phoneTV;
    private View myInfoView;

    private TextView tvGetPhone, tvPhone, tvQuestion, tvPassword, tvFriend, tvSetting;
    private ImageView ivEnsureFlag;
    private TextView tvEnsureFlag;
    private TextView tvEnsure;
    Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public String getBaseTag() {
        return Constant.TAG_MINE_FRAGMENT;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mine,
                container, false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        EventBus.getDefault().register(this);
        headImage = (ImageView) v.findViewById(R.id.image_head);
        phoneTV = (TextView) v.findViewById(R.id.phone);
        nicknameTV = (TextView) v.findViewById(R.id.nickname);
        myInfoView = v.findViewById(R.id.my_info);
        myInfoView.setOnClickListener(this);

        tvGetPhone = (TextView) v.findViewById(R.id.tv_get_phone);
        tvPhone = (TextView) v.findViewById(R.id.tv_phone);
        tvQuestion = (TextView) v.findViewById(R.id.tv_qustion);
        tvPassword = (TextView) v.findViewById(R.id.tv_password);
        tvFriend = (TextView) v.findViewById(R.id.tv_friend);

        tvEnsure = (TextView) v.findViewById(R.id.tv_ensure);
        tvEnsure.setOnClickListener(this);
        tvEnsureFlag = (TextView) v.findViewById(R.id.tv_ensure_flag);
        ivEnsureFlag = (ImageView) v.findViewById(R.id.iv_ensure_flag);
        tvSetting = (TextView) v.findViewById(R.id.tv_setting);

        tvEnsureFlag.setOnClickListener(this);
        tvPhone.setOnClickListener(this);
        tvGetPhone.setOnClickListener(this);
        tvQuestion.setOnClickListener(this);
        tvPassword.setOnClickListener(this);
        tvFriend.setOnClickListener(this);
        tvSetting.setOnClickListener(this);

        View actionbar = v.findViewById(R.id.action_bar);
        int statusBarHeight = 0;
        if (Constant.isStatusBar) {
            int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resId > 0) {
                statusBarHeight = getResources().getDimensionPixelSize(resId);
            } else {
                statusBarHeight = LocalDisplay.SCREEN_HEIGHT_PIXELS / 25;
            }
            actionbar.setPadding(0, statusBarHeight, 0, 0);
        }
        ViewGroup.LayoutParams lp = actionbar.getLayoutParams();
        lp.height = statusBarHeight + getResources().getDimensionPixelSize(R.dimen.height_title);
        actionbar.setLayoutParams(lp);


        mContext = this.getActivity();
        if (getUser() != null) {
            updateAvatar(getUser().getAvatar());
        }
        updateUserProfile();
        updateCertStatus();
    }


    public void updateUserProfile() {
        if (getActivity() == null) {
            return;
        }
        String token = getUser().getAccess_token();
        if (token == null || "".equals(token)) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.putExtra("flag", "main");
            startActivity(intent);

        } else {
            RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
            data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_profile);
            //data.setToken(getUser().getToken());

            data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("accountId", getUser().getAccountId());

            data.setParameters(map);
            request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_profile, onRequestListener);
        }
    }

    OnRequestListener<User> onRequestListener = new OnRequestListener<User>() {
        @Override
        public User jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, User.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<User> response, Object tag) {
            User user = response.getResponseElement();
            if (user == null || getActivity() == null) {
                return;
            }
            user.setAccess_token(getUser().getAccess_token());
            user.setAccountId(getUser().getAccountId());
            user.setPassword(getUser().getPassword());
            user.setTag(UUID.randomUUID().toString());
            user.setAccess_token(ApplicationHelper.getInstance().getUser().getAccess_token());
            updateUser(user);
            updateView(user);

        }
    };

    public void onResume() {
        if (getUser() != null) {
            updateView(getUser());
        }
        super.onResume();
    }


    private void updateView(User user) {
        updateAvatar(getUser().getAvatar());
        if (TextUtils.isEmpty(user.getNickname())) {
            nicknameTV.setVisibility(View.GONE);
        } else {
            nicknameTV.setVisibility(View.VISIBLE);
        }
        nicknameTV.setText(user.getNickname());
        if (user.getPhone() != null && user.getPhone().length() > 10)
            phoneTV.setText(user.getPhone().substring(0, 3) + "****" + user.getPhone().substring(7));
             /*
                    0:未认证；1：认证中；2：已认证；3：认证失败
                    * */
        /*if (user.isHasCert()) {
            // name_flagIV.setVisibility(View.VISIBLE);
            ivEnsureFlag.setVisibility(View.VISIBLE);
            tvEnsureFlag.setVisibility(View.VISIBLE);
        }
        if ("1".equals(getStoreInfo().getCertStatus())) {/////调整实名认证状态的一致性，都从storeinfo中获取该属性状态值
            tvEnsureFlag.setText("认证中");
            tvEnsureFlag.setVisibility(View.VISIBLE);
            ivEnsureFlag.setVisibility(View.GONE);
        } else if ("2".equals(getStoreInfo().getCertStatus())) {

            tvEnsureFlag.setText("已认证");
            tvEnsureFlag.setVisibility(View.VISIBLE);
            ivEnsureFlag.setVisibility(View.VISIBLE);
        } else if ("3".equals(getStoreInfo().getCertStatus())) {
            tvEnsureFlag.setText("认证失败");
            tvEnsureFlag.setVisibility(View.VISIBLE);
            tvEnsureFlag.setClickable(true);
            tvEnsure.setClickable(true);
            ivEnsureFlag.setVisibility(View.GONE);
        } else {

            tvEnsureFlag.setClickable(true);
            tvEnsure.setClickable(true);
            tvEnsureFlag.setText("未认证");
            ivEnsureFlag.setVisibility(View.GONE);
        }*/
        updateAvatar(user.getAvatar());
    }

    private void updateAvatar(String url) {
        String urlHead = null;
        if (url != null) {
            String[] split = url.split("-AVATAR?");
            if (split != null && split.length > 1) {
                urlHead = split[0];
            }
        }
        if (urlHead == null) {
            urlHead = url;
        }
        ImageLoader.getInstance().displayImage(urlHead, new ImageViewAware(headImage), BaseApplication.getAvatarOptions(url), null, null, null);

    }

    public void updateCertStatus() {
        //0,未开,1,开店,2,过,3,未过,4,冻结

        if (getActivity() != null && tvEnsureFlag != null) {
            MerChantInfo merchant = BaseApplication.getInstance().getMerchant();
            String storeStatus = merchant.getStoreStatus();

            if ("0".equals(storeStatus)) {
                tvEnsureFlag.setText("未认证");
            } else if ("1".equals(storeStatus)) {
                tvEnsureFlag.setText("认证中");
            } else if ("3".equals(storeStatus)) {
                tvEnsureFlag.setText("未通过");
            } else if ("2".equals(storeStatus)) {
                tvEnsureFlag.setText("已认证");
            } else if ("4".equals(storeStatus)) {
                tvEnsureFlag.setText("冻结中");
            } else {
                tvEnsureFlag.setText("未认证");

            }
        }
    }

    private void showCallPhoneDialog(){
        new IosAlertDialog(getActivity()).builder()
                .setMsg("400-0588-198")
                .setPositiveButton("拨打", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent_call0 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000588198"));//调出来拨打页面；
                        startActivity(intent_call0);
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) { }
        }).show();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_get_phone:
            case R.id.tv_phone:
                showCallPhoneDialog();
                break;
            case R.id.tv_qustion:
                help();
                break;
            case R.id.tv_password:
                Intent password = new Intent(getActivity(), ForgetPasdActivity.class);
                startActivity(password);
                break;
            case R.id.tv_friend:
                share();
                break;
            case R.id.tv_setting:
                Intent setting = new Intent(getActivity(), SetActivity.class);
                startActivity(setting);
                break;
/*2017年9月8日16:25:33最新需求所有都不能查看！
            case R.id.tv_ensure:
            case R.id.tv_ensure_flag:
            case R.id.iv_ensure_flag:
//                if (getUser().getCertStatus() != 1 && getUser().getCertStatus() != 2) {
//                    Intent ensure = new Intent(getActivity(), SelectNameEnsureActivity.class);
//                    startActivity(ensure);
//                }
                intoNames();
                 break;
*/
            case R.id.my_info:
                Intent info = new Intent(getActivity(),
                        MyInfoActivity.class);
                startActivity(info);
                break;

            default:
                break;
        }
    }


    private void intoNames() {
        String certStatus = getStoreInfo().getCertStatus();
        if (certStatus.equals("0")) {
            T.toast("去首页先进行店铺认证");
        } else/* if (certStatus.equals("1")) {
//                    T.toast("当前认证中，请耐心等待结果");
            getCertInfo();

        } else if (certStatus.equals("3")) {//认证失败
//                    T.toast("当前认证中，请耐心等待结果");
            getCertInfo();
        } else if (certStatus.equals("2")) */ {
            getCertInfo();
        }
    }

    private void help() {

        Intent intent = new Intent(getActivity(), WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_SUB_NORMAL);
        intent.putExtra(Constant.KEY_WEB_TITLE, "e批课堂");
        startActivity(intent);
    }

    ShareDialog dialog;
    private void share() {
        if (dialog == null)
            dialog = new ShareDialog(getActivity());
//        dialog.showDialog();
        dialog.showDialog(com.epfresh.api.constant.Constant.URL_SHARE_DOWNLOAD, "http://m.epfresh.com/images/app-logo.png", "国内领先的农产品交易服务平台，网上批发、产地直采，更省、更赚钱", "e批生鲜批发商APP");
    }

    public void getCertInfo() {

        RequestEntitySupply<StoreBaseInfo> RequestEntitySupply = new RequestEntitySupply<>();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_certInfo);
        request(RequestEntitySupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_certInfo, onCertInfoRequestListener);

    }

    private OnRequestListener<CertInfo> onCertInfoRequestListener = new OnRequestListener<CertInfo>() {
        @Override
        public CertInfo jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, CertInfo.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {

            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<CertInfo> response, Object tag) {

            hideProgressDialog();
            CertInfo ci = response.getResponseElement();

            intoCertView(ci);

        }
    };

    private void intoCertView(CertInfo ci) {

        if (ci != null) {
            String certStatus = getStoreInfo().getCertStatus();
            String certType = ci.getType();
            if ("3".equals(certStatus)) {//认证失败
                Intent intent = new Intent(getAppActivity(),
                        SelectNameEnsureActivity.class);
                intent.putExtra("certInfo", new Gson().toJson(ci));
                intent.putExtra("isFirst", false);
                intent.putExtra("certType", certStatus);
                intent.putExtra("certPersonCompanyType", certType);
                intent.putExtra("isMineIn", true);
                startActivity(intent);

            } else if ("1".equals(certStatus)) {//认证中
                if (certType.equals("1")) {//个人认证
                    Intent intent = new Intent(getAppActivity(),
                            EnsurePersonActivity.class);
                    intent.putExtra("certInfo", new Gson().toJson(ci));
                    intent.putExtra("isFirst", false);
                    intent.putExtra("certType", certStatus);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getAppActivity(),
                            EnsureCompanyActivity.class);
                    intent.putExtra("certInfo", new Gson().toJson(ci));
                    intent.putExtra("isFirst", false);
                    intent.putExtra("certType", certStatus);
                    startActivity(intent);
                }
            } else if ("2".equals(certStatus)) {//认证成功
                if (certType.equals("1")) {//个人认证
                    Intent intent = new Intent(getAppActivity(),
                            EnsurePersonActivity.class);
                    intent.putExtra("certInfo", new Gson().toJson(ci));
                    intent.putExtra("isFirst", false);
                    intent.putExtra("certType", certStatus);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getAppActivity(),
                            EnsureCompanyActivity.class);
                    intent.putExtra("certInfo", new Gson().toJson(ci));
                    intent.putExtra("isFirst", false);
                    intent.putExtra("certType", certStatus);
                    startActivity(intent);
                }
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void certStatusUpadteEvenbus(MineCertStatusEvenbus event) {
        updateCertStatus();
    }

}
